<template>
  <div class="app-container dirc">
    <!-- 基础信息 -->
    <el-card shadow="hover" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>任务信息</span>
        </div>
      </template>
      <el-descriptions :column="4">
        <el-descriptions-item label="项目名称">{{ formData?.activityName }}</el-descriptions-item>
        <el-descriptions-item label="节点">{{ formData?.nodeName }}</el-descriptions-item>
        <el-descriptions-item label="任务">{{ formData?.name }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ formData?.remark }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ formData?.username }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ formData?.status && ActivityNodeTask_Status_Label[formData.status] }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formData?.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ formData?.endTime }}</el-descriptions-item>
      </el-descriptions>
      <div v-if="formData?.status == ActivityNodeTaskStatus.NOT_START" class="mt30 disf alc juc">
        <el-button type="primary" @click="startTask">开始任务</el-button>
      </div>
    </el-card>
    <!-- 填报信息 -->
    <el-card class="mt10" style="overflow-y: auto" shadow="hover" v-loading="loading" v-if="formData?.status == ActivityNodeTaskStatus.PROCESSING ||
      formData?.status == ActivityNodeTaskStatus.COMPLETED ||
      formData?.status == ActivityNodeTaskStatus.AUDITING
      ">
      <template #header>
        <div class="card-header">
          <span v-if="formData?.status == ActivityNodeTaskStatus.AUDITING">任务审核</span>
          <span v-else>任务填报</span>
        </div>
      </template>
      <el-form ref="form" label-width="120px" v-if="formData.hasFillRole ||
      (formData.status == ActivityNodeTaskStatus.AUDITING && formData.hasAuditRole) ||
      formData.status == ActivityNodeTaskStatus.COMPLETED
      ">
        <el-form-item v-for="item in formData?.dataConfigs" :key="item.id" :label="item.property">
          <template v-if="formData.status == ActivityNodeTaskStatus.PROCESSING">
            <!-- 数据类型：TEXT -->
            <el-input v-if="item.dataType == FlowTaskDataType.TEXT" v-model="item.val"
              :placeholder="`请输入${item.property}`" style="width: 600px"></el-input>
            <!-- 数据类型：NUMBER -->
            <el-input-number v-if="item.dataType == FlowTaskDataType.NUMBER" v-model="item.val" style="width: 150px"
              :min="0" />
            <!-- 数据类型：OPTION -->
            <el-radio-group v-if="item.dataType == FlowTaskDataType.OPTION && item.optionsList.length <= 3"
              v-model="item.val">
              <el-radio v-for="option in item.optionsList" :key="option" :label="option">
                {{ option }}
              </el-radio>
            </el-radio-group>
            <el-select v-if="item.dataType == FlowTaskDataType.OPTION && item.optionsList.length > 3" v-model="item.val"
              style="width: 260px" placeholder="请选择">
              <el-option v-for="option in item.optionsList" :key="option" :label="option" :value="option"></el-option>
            </el-select>
            <!-- 数据类型：DATE -->
            <el-date-picker v-if="item.dataType == FlowTaskDataType.DATE" v-model="item.val"
              value-format="YYYY-MM-DD" />
            <!-- 数据类型：DATETIME -->
            <el-date-picker v-if="item.dataType == FlowTaskDataType.DATETIME" type="datetime" v-model="item.val"
              value-format="YYYY-MM-DD HH:mm:ss" />
            <!-- 数据类型：FILE -->
            <FileUpload v-if="item.dataType == FlowTaskDataType.FILE" v-model="item.valList as Attachment[]"
              :data="{ businessType: FileBusinessType.ACTIVITY_TASK_ITEM, businessId: formData.id }" :limit="9" />
          </template>
          <template v-else>
            <!-- 文件 -->
            <Attachments v-if="item.dataType == FlowTaskDataType.FILE" :attachments="item.valList" />
            <!-- 普通类型 -->
            <span v-else>{{ item.val }}</span>
          </template>
        </el-form-item>
        <el-form-item v-if="formData?.status == ActivityNodeTaskStatus.PROCESSING">
          <el-button @click="saveTask">保存</el-button>
          <el-button type="primary" @click="endTask">保存并提交</el-button>
        </el-form-item>
      </el-form>
      <!--审批-->
      <el-form ref="auditFormRef" label-width="120px"
        v-if="formData.status == ActivityNodeTaskStatus.AUDITING && formData.hasAuditRole">
        <el-form-item label="审批意见">
          <el-input v-model="auditFormData.remark" placeholder="请输入审批意见" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="auditTask(false)">退回</el-button>
          <el-button type="primary" @click="auditTask(true)">通过</el-button>
        </el-form-item>
      </el-form>

    </el-card>
    <detailHistory :taskId="id" :activityRole="formData?.activityRole"></detailHistory>

  </div>
</template>

<script lang="ts" setup>
import FileUpload from "@/components/Upload/FileUpload.vue";
import Attachments from "@/components/Upload/Attachments.vue";
import ActivityNodeTaskAPI, {
  ActivityNodeTask_Status_Label,
  ActivityNodeTaskDetail,
  ActivityNodeTaskFillForm,
  ActivityNodeTaskStatus,
  AuditForm,
} from "@/api/flow/activityNodeTask.api";
import { FlowTaskDataType } from "@/api/flow/flowNodeTask.api";
import FileAPI, { FileBusinessType } from "@/api/file.api";
import { Attachment } from "@/api/common/common";
import detailHistory from "./detailHistory.vue";

defineOptions({
  name: "ActivityTaskDetail",
  inheritAttrs: false,
});

const route = useRoute();
const id = ref("");
const loading = ref(false);
const formData = ref<ActivityNodeTaskDetail>(); //合同信息
const auditFormData = ref<AuditForm>({
  taskId: id.value,
  remark: "",
  result: false,
}); //审核信息

onActivated(() => {
  if (route.query.id == id.value) return;
  id.value = route.query.id as string;
  loadDetail();
});

const loadDetail = async () => {
  if (!id.value || id.value === "0") {
    return;
  }
  loading.value = true;
  try {
    const data = await ActivityNodeTaskAPI.loadDetail(id.value);
    const record = data.records && data.records[data.records.length - 1];
    // 加载附件
    const files = await FileAPI.loadByBusiness(id.value, FileBusinessType.ACTIVITY_TASK_ITEM);
    data.dataConfigs.forEach(async (item, idx) => {
      item.val = record && record.items[idx].val;
      item.valList = [];
      if (item.dataType == FlowTaskDataType.FILE) {
        // 恢复附件
        const fileList = item.val && item.val.split(",");
        if (fileList) {
          item.valList = files.filter((file) => fileList.includes(file.id!));
        }
      }
      if (item.options) {
        item.optionsList = item.options.split(",");
        if (item.optionsList.length <= 3 && !item.val) {
          item.val = item.optionsList[0];
        }
      }
    });
    formData.value = data;
  } catch (error) {
    console.error(error);
  }
  loading.value = false;
};

/**
 * 开始任务
 */
function startTask() {
  ElMessageBox.confirm("确认开始任务?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ActivityNodeTaskAPI.start(id.value).then(() => {
      ElMessage.success("开始任务成功");
      loadDetail();
    });
  });
}

/**
 * 保存任务
 */
function saveTask() {
  loading.value = true;
  saveTaskFill(() => {
    ElMessage.success("保存成功");
    loading.value = false;
  });
}

// 保存任务填报
function saveTaskFill(callback?: () => void) {
  const sendData: ActivityNodeTaskFillForm = {
    taskId: id.value,
    remark: formData.value?.remark || "",
    items:
      formData.value?.dataConfigs.map((c) => {
        return {
          dataType: c.dataType,
          property: c.property,
          val: c.valList && c.valList.length ? c.valList.map((f) => f.id).join(",") : c.val,
        };
      }) || [],
  };
  ActivityNodeTaskAPI.fill(sendData)
    .then(() => {
      callback && callback();
    })
    .catch(() => {
      loading.value = false;
    });
}

/**
 * 提交任务
 */
function endTask() {
  ElMessageBox.confirm("确认所有填报内容已完成，并提交任务?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    saveTaskFill(() => {
      loading.value = true;
      ActivityNodeTaskAPI.complete(id.value)
        .then(() => {
          ElMessage.success("提交任务成功");
          loadDetail();
        })
        .finally(() => {
          loading.value = false;
        });
    });
  });
}

function auditTask(pass: boolean) {
  loading.value = true;
  auditFormData.value.result = pass;
  auditFormData.value.taskId = id.value;
  ActivityNodeTaskAPI.audit(auditFormData.value)
    .then(() => {
      ElMessage.success("审核任务成功");
      loadDetail();
    })
    .finally(() => {
      loading.value = false;
    });
}
</script>

<style lang="scss" scoped></style>
